package com.jx.service.system;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jx.dao.system.UserDao;
import com.jx.pojo.entity.system.User;
import com.jx.pojo.vo.system.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 用户管理
 */
@Service
@Slf4j
public class UserService extends ServiceImpl<UserDao, User> {

    @Resource
    private UserRoleService userRoleService;

    /**
     * 分页查询用户
     */
    public PageInfo<User> listPage(UserVO query) {
        PageHelper.startPage(query.getPageNum(),query.getPageSize());
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(query.getUsername()),User::getUsername,query.getUsername());
        wrapper.like(StringUtils.isNotBlank(query.getAccount()),User::getAccount,query.getAccount());
        wrapper.like(StringUtils.isNotBlank(query.getPhone()),User::getPhone,query.getPhone());
        wrapper.like(query.getStatus() != null,User::getStatus,query.getStatus());
        List<User> list = this.list(wrapper);
        return new PageInfo<>(list);
    }

    @Transactional
    public void saveUser(User user) {
        // 保存用户信息
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        this.saveOrUpdate(user);

        // 保存用户对应的角色数据
        userRoleService.saveUserRole(user,user.getRoleIds());
    }

    /**
     * 获取详情
     */
    public User getUserById(Integer id) {
        User user = this.getById(id);
        List<Integer> roleIds = userRoleService.getRoleIdsByUserId(user.getId());
        user.setRoleIds(roleIds);
        return user;
    }

    /**
     * 根据账号获取用户
     */
    public User getUserByAccount(String account) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getAccount,account);
        return this.getOne(wrapper);
    }



}
